package indi.zhifa.recipe.bailan.framework.auth.entity.dto.encrypt;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.SM3;
import indi.zhifa.recipe.bailan.framework.common.entity.exception.ServiceException;
import org.springframework.util.StringUtils;

/**
 * Description:
 * @Copyright: Copyright (c) 2020-2028 北京华咨电力科技发展有限公司 All rights reserved.
 * @author: 褚智勇(hataksumo@163.com)
 * @date:  2022/4/25 14:40
 */
public class Sm3Encrypt {

    private final SM3 mSm3;
    private final String mSalt;
    static final int RAND_STR_LEN = 8;

    public Sm3Encrypt(){
        mSalt = RandomUtil.randomString(RAND_STR_LEN);
        mSm3 = new SM3();
    }

    public Sm3Encrypt(String pSalt){
        mSalt = pSalt;
        mSm3 = new SM3();
    }

    public String encode(String pText){
        String decryptStr = mSm3.digestHex(pText + mSalt)+ mSalt + pText;
        return decryptStr;
    }

    public String digest(String pText){
        return mSm3.digestHex(pText);
    }

    public boolean valid(String pSignedText){
        if(!StringUtils.hasText(pSignedText) || pSignedText.length() <= 72){
            throw new ServiceException("字符串为空或长度不够");
        }

        String signedStr = pSignedText.substring(0,64);
        String salt = pSignedText.substring(64,72);
        String orgText = pSignedText.substring(72);
        if(!salt.equals(mSalt)){
            throw new ServiceException("盐值被修改");
        }
        String testSignedStr = mSm3.digestHex(orgText + mSalt);
        if(!signedStr.equals(testSignedStr)){
            throw new ServiceException("签名验证不合法");
        }
        return true;
    }

}
